
var cartType=GetQueryString("cartType");
$(function(){
	//alert($(".all_goods p a").eq('all'));
	$(".all_goods p a").eq(0).removeClass("selected");
	$(".all_goods p a").each(function(){
		//alert($(this).html());
	    if($(this).attr("id") == cartType){
	    	$(this).addClass("selected");
	    }
	 });
/*	//>>>>>>>购物车页<<<<<<<
	$('.shopping_cart li .delete').click(function(){
		var $n = $(this).parents('.item').find('.product').length;
		if($n < 2){
			$(this).parents('.item').remove();
		}
		$(this).parent().remove();
		getTotal();
	});*/
	
	//计算总金额，总件数
	function getTotal(){
		var $price = 0;
		var $selected = 0;
		var $number = 0;
		var $money = 0;
		for(var i = 0;i<$('.product').length;i++){
			if($('.product').eq(i).find("input[type='checkbox']").is(":checked")){  
				var $money = $('.product').eq(i).find('.unit_price').text();
				var $number = $('.product').eq(i).find('.amount').find('input').val()*1;
				console.log(typeof($number))
				$price += parseFloat($money * $number);
				$selected += parseInt($number);
			}
		};
		$('.all_goods .sum').text($selected);
		$('.all_goods .totalprice').text("￥" + $price.toFixed(2));
		$("#totalAmount").val($price.toFixed(2))
		var $number = $('.all_goods div .sum').text();
		if($number > 0){
			$('.shopping_cart button').addClass('active');
		}else{
			$('.shopping_cart button').removeClass('active');
		}

	    updateCartNum();
	};
	
	$('.shopping_cart .all_goods .item > p input').click(function(){
		$(this).parent().siblings().find('input').prop('checked',this.checked);
		getTotal();
	});
	
	$('.shopping_cart :checkbox[name=items]').click(function(){
		getTotal();
	});
	
//	$('.shopping_cart button').click(function(){
//		getTotal();
//	});
	 //选中一个商品
	$('.shopping_cart :checkbox[name=items]').change(function() {
		 updateCartNum();
	});

	  // 点击店铺按钮
	$('.shopping_cart .checkedAll').change(function() {
		 updateCartNum();
	});
	//全选
	$('.shopping_cart .checkedAll').click(function(){
		$('.shopping_cart :checkbox').prop('checked', this.checked);		
		getTotal();
		//获取选中要结算的商品
		var $checkedBtn = $('.shopping_cart :checkbox[name=items]:checked');
		var ids ="";
		for(var i =0; i< $checkedBtn.length; i++){
			ids += $($checkedBtn[i]).val() + ",";
		}
		$("#ids").val(ids);
	});
	//删除选中的
	$('.shopping_cart .deleteChecked').click(function(){
		var $checkedBtn = $('.shopping_cart :checkbox[name=items]:checked');
		var ids ="";
		for(var i =0; i< $checkedBtn.length; i++){
			ids += $($checkedBtn[i]).val() + ",";
		}
		//$checkedBtn.parents('li').remove();
		deleteAllProduct (ids);
	});
	//将选中的商品移入到收藏夹
	$('.shopping_cart .moveToFavorites').click(function(){
		var $checkedBtn = $('.shopping_cart :checkbox[name=items]:checked');
		var ids ="";
		for(var i =0; i< $checkedBtn.length; i++){
			ids += $($checkedBtn[i]).val() + ",";
		}
		moveToFavorites(ids);
	});
	
	//更新购物车结算数量
	function updateCartNum(){
		   var checkNum=0;
		   $('.shopping_cart :checkbox[name=items]:checked').each(function(){
				var quantity = $(this).parents(".product").find(".shu").val();
				checkNum+=parseInt(quantity);
		    });
		    $(".tallMonut").text(checkNum);
	}
	//加法
	$('.shopping_cart .amount .add').click(function(){

		var aa = $(this).parents('.failure').hasClass('failure');
		if(!aa){
			var $number = $(this).prev().val();
			var $unit_price = $(this).parents('.product').find('.unit_price').text();
			var $input_ = $(this).parents('.product').find('input[name=items]');
			console.log($unit_price)
			$number ++;
	
			//获取商品库存
			var goodsSkuInfos = $(this).prev().attr("goodsSkuInfos");
			var productId = $(this).prev().attr("productId");
			var result = getGoodsStockBySkuValues(productId,goodsSkuInfos);//根据商品规格请求商品库存
		    if(CommnUtil.notNull(result)){
		    	 if(CommnUtil.notNull(result.stock)){
	    			if($number  > result.stock){
	    				layer.msg('商品库存不足',{offset: ['40%', '40%'],/*title: ['提醒', 'font-size:18px;'],*/icon: 2,time:10000});
	    				$number = result.stock;
	    			}
		    	 }
		    }
			$(this).prev().val($number);
			$(this).parents('.product').find('.money').text(($number * $unit_price).toFixed(2));
			if($input_.is(":checked")){
				getTotal();
			}
			var id = $(this).prev().attr("cartId"); 
			//alert(id);
			//请求修改商品数量
			updateProduct(id,$number);
		}
	});
	//减法
	$('.shopping_cart .all_goods ul li .amount .minus').click(function(){
		var $number = $(this).next().val();
		var $unit_price = $(this).parents('.product').find('.unit_price').text();
		var $input_ = $(this).parents('.product').find('input[name=items]');
		//获取商品库存
		var goodsSkuInfos = $(this).next().attr("goodsSkuInfos");
		var productId = $(this).next().attr("productId");
		var result = getGoodsStockBySkuValues(productId,goodsSkuInfos);//根据商品规格请求商品库存
	    if(CommnUtil.notNull(result)){
	    	 if(CommnUtil.notNull(result.stock)){
    			if($number  > result.stock){
    				layer.msg('商品库存不足',{offset: ['40%', '40%'],/*title: ['提醒', 'font-size:18px;'],*/icon: 2,time:10000});
    				$number=result.stock;
    			}
	    	 }
	    }
		if($number > 1){
			$number --;
			$(this).next().val($number);
			$(this).parents('.product').find('.money').text(($number * $unit_price).toFixed(2));
		}
		if($input_.is(":checked")){
			getTotal();
		}

		var id = $(this).next().attr("cartId"); 
		//alert(id);
		//请求修改商品数量
		updateProduct(id,$number);
	});
    //监听购物车商品数量变化，计算商品单价与总金额
	$('.shopping_cart .amount input').change(function(){
		getTotal();
		var $number = $(this).val()-1;
		var $unit_price = $(this).parents('.product').find('.unit_price').text();
		var $input_ = $(this).parents('.product').find('input[name=items]');
		console.log($unit_price)
		$number ++;
		
		//获取商品库存
		var goodsSkuInfos = $(this).attr("goodsSkuInfos");
		var productId = $(this).attr("productId");
		var result = getGoodsStockBySkuValues(productId,goodsSkuInfos);//根据商品规格请求商品库存
	    if(CommnUtil.notNull(result)){
	    	 if(CommnUtil.notNull(result.stock)){
    			if($number  > result.stock){
    				layer.msg('商品库存不足',{offset: ['40%', '40%'],/*title: ['提醒', 'font-size:18px;'],*/icon: 2,time:10000});
    				$number = result.stock;
    			}
	    	 }
	    }

		$(this).val($number);
		$(this).parents('.product').find('.money').text(($number * $unit_price).toFixed(2));
		if($input_.is(":checked")){
			getTotal();
		}

		var id = $(this).attr("cartId"); 
		//alert(id);
		//请求修改商品数量
		updateProduct(id,$number);
	});
	
	
	//编辑规格
	$('.shopping_cart .editable').hover(function(){
		$(this).find('a').css('display','block');
	},function(){
		$(this).find('a').css('display','none');
	})
	$('.shopping_cart .editable a').click(function(){
		$(this).parent().siblings('.param_layer').slideToggle(200);
	});
	
	$('.shopping_cart .yes').click(function(){
		$(this).parents('.param_layer').slideUp(200);
		var $size = $(this).parent().find('.size .selected').text();
		var $color = $(this).parent().find('.color .selected').text();
		$color = '颜色:' + $color;
		$size = '尺码:' + $size;
		$(this).parents('.wrap').find('.editable .s_color').text($color);
		$(this).parents('.wrap').find('.editable .s_size').text($size);
		

		
		//修改规格
		var $color_sku_valueId =  $(this).parent().find('.color .selected').attr('id');
		var $size_sku_valueId =$(this).parent().find('.size .selected').attr('id');
		var $goods_sku_id = $color_sku_valueId +"," +$size_sku_valueId;		
		var $goods_sku_info = $color +"," +$size;		
		
		var id = $(this).parent().find('.size .selected').attr("cartId"); 
		//alert(id);
		//请求修改商品规格信息
		updateProductSkuInfo(id,$goods_sku_id,$goods_sku_info);
	});
	
	$('.shopping_cart .no').click(function(){
		$(this).parents('.param_layer').slideUp(200);
	});
	
	$('.shopping_cart .param_layer .left p a').click(function(){
		$(this).addClass('selected').siblings().removeClass('selected');
	});
	
	//结算
	$(".tallyOrders").on("click",function(){
		debugger;
		//获取选中要结算的商品
		var $checkedBtn = $('.shopping_cart :checkbox[name=items]:checked');
		if($checkedBtn.length == 0){
			 layer.msg("请选择商品",{icon:2,skin: 'layui-layer-red ',offset: ['40%', '45%']});
			 return false;
		}
		var url = rootPath + "/order/tallyOrders";
		var index = layer.load(5,{offset: ['50%', '50%']}); //进度条 遮罩
		var ids ="";
		for(var i =0; i< $checkedBtn.length; i++){
			ids += $($checkedBtn[i]).val() + ",";
		}
		var result = CommnUtil.ajax(url,
				{ids:ids},
				"html");

		result = JSON.parse(result);
		if (result.flag) {
			if(CommnUtil.notNull(result.stockMessage)){
			    // layer.msg(result.stockMessage,{offset: ['40%', '40%'],/*title: ['提醒', 'font-size:18px;'],*/icon: 1,time:100000});
				 layer.msg(result.stockMessage,{icon:2,skin: 'layui-layer-red ',offset: ['40%', '45%']});	
		         Pause(this,6000);//调用暂停函数
			}else{
				//var jsonStr = JSON.stringify(result);  
				var $url = rootPath + '/order/confirm_order';		
				window.open($url,'_self'); 
			}

			layer.close(index);
		}else if(result.sessionValid){
			 reLogin();
			 layer.close(index);
		} else {
			 layer.msg('结算失败',{icon:2,skin: 'layui-layer-red ',offset: ['40%', '45%']});	
	         Pause(this,6000);//调用暂停函数
		     this.NextStep=function(){
				reloadShopCart();
				layer.close(index);
		     }
		}
		
	});
	

});

//根据商品ID和规格请求商品库存
function getGoodsStockBySkuValues(productId,goodsSkuInfos){
	var url = rootPath + '/cart/getGoodsStockBySkuValues';
	var result = CommnUtil.ajax(url, {
		productId : productId,
		goods_sku_info:goodsSkuInfos
	}, "json");	
	console.log(result);
	return result;
}
//修改购物车商品数量
function updateProduct(id,quantity){
	var url = rootPath + '/cart/updateProduct';
	var result = CommnUtil.ajax(url, {
		id : id,
		quantity:quantity
	}, "json");	
	reloadShopCart();
	console.log(result);
	updateCartNum();
}
//修改购物车规格信息
function updateProductSkuInfo(id, goods_sku_id,goods_sku_info){
	var url = rootPath + '/cart/updateProductSkuInfo';
	var result = CommnUtil.ajax(url, {
		id : id,
		goods_sku_id:goods_sku_id,
		goods_sku_info:goods_sku_info
	}, "json");	
	reloadShopCart();
	//console.log(result);
	updateCartNum();
}
//删除购物车商品
function deleteProduct(obj){
	var id = $(obj).attr("id");
	layer.confirm('确认要删除该宝贝吗？',{skin: 'layui-layer-red ',offset: ['40%', '40%']},function(index){
		var url = rootPath + '/cart/deleteProduct';
		var result = CommnUtil.ajax(url, {
			id : id
		}, "json");
		if (result.flag) {
	        layer.msg('删除成功!',{icon:1,skin: 'layui-layer-red ',offset: ['40%', '45%']});	
	        Pause(this,6000);//调用暂停函数
		    this.NextStep=function(){
				reloadShopCart();
		    }
			getTotal();
		}else {
			 layer.msg('删除失败',{icon:2,skin: 'layui-layer-red ',offset: ['40%', '45%']});	
	         Pause(this,6000);//调用暂停函数
		     this.NextStep=function(){
			 	reloadShopCart();
		     }
			getTotal();
		}
	});
}
//添加收藏
function addFavorites(obj){
	var id = $(obj).attr("id");
	layer.confirm('确认移入到收藏夹吗？',{skin: 'layui-layer-red ',offset: ['40%', '40%']},function(index){
		var url = rootPath + '/cart/moveToFavorites';
		var data = {};
		data["ids"] = id;
		data["collectionType"] = "1";  //收藏类型 1：商品，2：店铺 
		var result = CommnUtil.ajax(url, data, "json");
		if (result.resultSuccess) {
			 layer.msg('移入收藏夹成功',{icon:1,skin: 'layui-layer-red ',offset: ['40%', '45%']});	
	         Pause(this,6000);//调用暂停函数
		     this.NextStep=function(){
			 	reloadShopCart();
		     }
			getTotal();
		}else {
			 layer.msg('移入收藏夹失败',{icon:2,skin: 'layui-layer-red ',offset: ['40%', '45%']});	
	         Pause(this,6000);//调用暂停函数
		     this.NextStep=function(){
			 	reloadShopCart();
		     }
			getTotal();
		}
	});
}
//将选中的商品移入收藏夹
function moveToFavorites(ids){
	if (ids == "") {
		layer.msg("请选择要收藏的商品！",{skin: 'layui-layer-red ',offset: ['40%', '45%']});
		return;
	}
	var data ={};
	data["ids"] = ids;
	data["collectionType"] = "1";  //收藏类型 1：商品，2：店铺 
	layer.confirm('确认移入收藏夹吗？',{skin: 'layui-layer-red ',offset: ['40%', '45%']},  function(index) {
		var url = rootPath + '/cart/moveToFavorites';
		var result = CommnUtil.ajax(url, data, "json");
		if (result.resultSuccess) {
			 layer.msg('移入收藏夹成功',{icon:1,skin: 'layui-layer-red ',offset: ['40%', '45%']});	
	         Pause(this,6000);//调用暂停函数
		     this.NextStep=function(){
			 	reloadShopCart();
		     }
			getTotal();
		}else if(result.sessionValid){
			 reLogin();
		} else {
			 layer.msg('移入收藏夹失败',{icon:2,skin: 'layui-layer-red ',offset: ['40%', '45%']});	
	         Pause(this,6000);//调用暂停函数
		     this.NextStep=function(){
			 	reloadShopCart();
		     }
			getTotal();
		}
	});
}
//回到购物车列表页面
function reloadShopCart(){
	window.location.href=rootPath + '/cart/cartPage?cartType=all';
}
//删除勾选的购物车商品
function deleteAllProduct (ids){
	if (ids == "") {
		layer.msg("请选择删除项！！",{skin: 'layui-layer-red ',offset: ['40%', '45%']});
		return;
	}
	layer.confirm('确认要删除该宝贝吗？',{skin: 'layui-layer-red ',offset: ['40%', '45%']},  function(index) {
		var url = rootPath + '/cart/deleteAllProduct';
		var result = CommnUtil.ajax(url, {
			ids : ids
		}, "json");
		if (result.flag) {
			 layer.msg('删除成功',{icon:1,skin: 'layui-layer-red ',offset: ['40%', '45%']});	
	         Pause(this,6000);//调用暂停函数
		     this.NextStep=function(){
			 	reloadShopCart();
		     }
			getTotal();
		} else {
			 layer.msg('删除失败',{icon:2,skin: 'layui-layer-red ',offset: ['40%', '45%']});	
	         Pause(this,6000);//调用暂停函数
		     this.NextStep=function(){
			 	reloadShopCart();
		     }
			getTotal();
		}
	});
}
//重新登录页面
function reLogin(){
	window.location.href=rootPath + '/member/loginPre?redirect=/cart/cartPage?cartType=all';
}
//清除因商品库存不足而失效的商品
function clearShortStockInvalidPorduct(){
	layer.confirm('确认要清空失效的宝贝吗？',{skin: 'layui-layer-red ',offset: ['40%', '45%']},  function(index) {
		var url = rootPath + '/cart/clearShortStockInvalidPorduct';
		var result = CommnUtil.ajax(url, {
		}, "json");
		if (result.flag) {
			 layer.msg('清空成功',{icon:1,skin: 'layui-layer-red ',offset: ['40%', '45%']});	
	         Pause(this,6000);//调用暂停函数
		     this.NextStep=function(){
			 	reloadShopCart();
		     }
			getTotal();
		}else if(result.sessionValid){
			 reLogin();
		} else {
			 layer.msg('清空失败',{icon:2,skin: 'layui-layer-red ',offset: ['40%', '45%']});	
	         Pause(this,6000);//调用暂停函数
		     this.NextStep=function(){
			 	reloadShopCart();
		     }
			getTotal();
		}
	});
}